<template>
  <div>
    <el-dialog title="试验周期信息" :visible.sync="dialogVisible" width="50%" @close="dialogVisible = false">
        <div>
           <el-form ref="form" :model="formdata" label-width="100px" label-position="left" :disabled="isupdate">
               <el-row :gutter="20">
                   <el-col :span="12">
                    <el-form-item label="用户名称">
                      <FilterSelect2
                        v-model="formdata.orgNo"
                        :optionlist="qiyelist"
                        @updateModelValue="changeqiye"
                        :valuekey="{ name: 'bizOrgName', value: 'bizOrgNo' }"
                      ></FilterSelect2>
                    </el-form-item>
                   </el-col>
                   <el-col :span="12">
                    <el-form-item label="配电房">
                      <!-- <el-select size="small" v-model="formdata.powerDistributionId" filterable  style="width: 100%;" placeholder="选择消状态" clearable>
                        <el-option label="已消缺" value="0" />
                        <el-option label="未消缺" value="1" />
                      </el-select> -->
                      <FilterSelect2
                        v-model="formdata.powerDistributionId"
                        :optionlist="peidianlist"
                        :valuekey="{ name: 'name', value: 'id' }"
                      ></FilterSelect2>
                    </el-form-item>
                   </el-col>
               </el-row>
               <el-row :gutter="20">
                   <el-col :span="12">
                    <el-form-item label="试验类型">
                      <FilterSelect2
                          v-model="formdata.testType"
                          :optionlist="shiyanlist"
                          :valuekey="{ name: 'text', value: 'value' }"
                        ></FilterSelect2>
                    </el-form-item>
                   </el-col>
                   <el-col :span="12" >
                      <el-form-item label="设备名称" >
                        <!-- <el-select v-model="equipName"  placeholder="请输入设备" multiple filterable
                         clearable size="small" style="width:100%" @change="changedevice">
                          <el-option v-for="item in shebeilist" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select> -->
                        <el-select @clear="clear" v-model="equipName" @remove-tag="removetag" multiple  size="small" style="width: 100%;" clearable>
                          <el-option value="id" label="name" style="height: auto">
                            <el-tree
                              ref="tree"
                              :props="prop"
                              :highlight-current="true"
                              @node-click="handleNodeClick"
                              :load="loadNode"
                              lazy>
                            </el-tree>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
               </el-row>
               <el-row :gutter="20">
                   <el-col :span="12">
                     <el-form-item label="上次试验日期">
                      <el-date-picker
                        v-model="formdata.lastTestDate"
                        type="date"
                        size="small"
                        style="width:100%"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期">
                      </el-date-picker>
                     </el-form-item>
                   </el-col>
                   <el-col :span="12">
                     <el-form-item label="下次试验日期">
                      <el-date-picker
                        v-model="formdata.nextTestDate"
                        type="date"
                        size="small"
                        style="width:100%"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期">
                      </el-date-picker>
                     </el-form-item>
                   </el-col>
               </el-row>
               <el-row :gutter="20">
                   <el-col :span="24">
                     <el-form-item label="试验内容">
                       <el-input type="textarea" v-model="formdata.content"></el-input>
                     </el-form-item>
                   </el-col>
               </el-row>
           </el-form>
        </div>
        <div slot="footer">
            <el-button  size="small" @click="dialogVisible = false">取 消</el-button>
            <el-button v-show="!isupdate" size="small" type="primary" @click="sure">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { getgenjiedianapi, getzijidianapi } from '@/api/monitor'
import {geipeidiansapi,getshebeiapi} from '@/api/keynote'
import {posttestcycleapi,puttestcycleapi} from '@/api/system/TestCycle'
export default {
  name: 'CallPoliceDialog',
  props:{
    isshow:{
      type:Boolean,
      default:false
    },
    qiyelist:{
      type:Array,
      default:()=>[]
    },
    shiyanlist:{
      type:Array,
      default:()=>[]
    }
  },
  data() {
    return {
      isupdate:false,
      equipName: [],
      selectedEquips:[],
      formdata:{},
      shebeilist:[],
      peidianlist:[],
      dialogVisible: false,
      prop: {
        label: 'name',
        disabled:'disabled'
      }
    };
  },

  mounted() {
    
  },

  methods: {
    // 确认
    async sure() {
      const ids = this.selectedEquips.map(ele => ele.id).join(',')
      this.formdata.id ? await puttestcycleapi({
        content: this.formdata.content, deviceId: ids,
        lastTestDate: this.formdata.lastTestDate, testType: this.formdata.testType,
        nextTestDate: this.formdata.nextTestDate, orgNo: this.formdata.orgNo,
        powerDistributionId: this.formdata.powerDistributionId,id:this.formdata.id
      }).then(res => {
        this.getmessage(res,'修改')
      }):
      await posttestcycleapi({...this.formdata,deviceIds:ids}).then(res=>{
        this.getmessage(res,'新增')
      })
    },
    changedevice(val) {
      if (this.formdata.id&&val.length > 1) this.equipName = [this.equipName[this.equipName.length - 1]];
    },
    // 修改/浏览
    async updateform(row,flag) {
      this.isupdate=flag?flag:false
      this.$set(this.formdata,'orgNo',row.orgNo)
      await this.changeqiye(row.orgNo)
      // await this.changepei(row.powerDistributionId)
      const {powerDistributionId,...obj}=row
      this.formdata = { ...obj, powerDistributionId: String(powerDistributionId) }
      this.dialogVisible=true
      this.$set(this,'equipName',[row.deviceName])
      this.$set(this,'selectedEquips',[{name:row.deviceName,id:row.deviceId}])
    },
    // 设备树选择
    handleNodeClick(val) {
      if (this.formdata.id) {
        this.$set(this,'equipName',[val.name])
        this.$set(this,'selectedEquips',[{name:val.name,id:val.id}])
      } else {
        const isSelected = this.selectedEquips.some(item => item.id === val.id);
        if (!isSelected) {
          // 如果未选中，则添加到 selectedEquips 数组
          this.selectedEquips.push({ name: val.name, id: val.id });
          this.equipName=this.selectedEquips.map(ele=>ele.name)
        }
      }
      
    },
    removetag(val) {
      const index = this.selectedEquips.findIndex(item => item.name === val);
      if (index!== -1) {
        this.selectedEquips.splice(index, 1);
      }
    },
    clear() {
      this.equipName=this.selectedEquips=[]
    },
    // 企业下拉获取配电室
    async changeqiye(id){
      const {data:{list}} = await geipeidiansapi({ orgNo: id })
      this.peidianlist = list
      this.formdata.powerDistributionId=''
      this.shebeilist=[]
    },
    // 配电室下拉获取设备
    // async changepei(id){
    //   const {data:{list}} = await getshebeiapi({orgNo: this.formdata.orgNo, pathId: id })
    //   this.shebeilist = list
    //   this.equipName=[]
    // },
    quxiao() {
      this.equipName=this.selectedEquips=this.peidianlist=[]
      this.formdata = {}
      this.isupdate=false
    },
    getmessage(res, name) {
      this.$message({
          type:res.code=='200'?'success':'warning',
          message: res.code == '200' ? `${name}成功`:res.message
      })
      if(res.code == '200')this.dialogVisible=false
      if(res.code == '200')this.$emit('togetlist')
    },
    // 树组件懒加载
    async loadNode(node, resolve) {
      const res = await getgenjiedianapi({ treeModel: 'DeviceManageTree' })
      if (node.level === 0) {
        // 初始的级数（最顶层）
        const ress = await getzijidianapi(res.data.list[0])
        return resolve(ress.data.list)
      }
      if (node.level > 0) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }
    }
  },
  watch:{
    dialogVisible(val){
      if(!val)this.quxiao()
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__footer{
  text-align: center;
}
</style>